# -*-coding: Utf-8 -*-
# @File : 12 .py
# author: 石明亮
# Time：2024/2/19
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

# 发信方的信息：发信邮箱，QQ 邮箱授权码
from_addr = '1504381150@qq.com'
password = 'aotllkxkxezdjihf'  # 注意：实际使用时不要将密码直接写在代码中
# 收信方邮箱
to_addr = '1608103725@qq.com'
# 发信服务器
smtp_server = 'smtp.qq.com'
html_msg ="""<p>Python 邮件发送HTML格式⽂件测试...</p>"""
# 邮箱正文内容，第一个参数为内容，第二个参数为格式(plain 为纯文本)，第三个参数为编码
msg = MIMEMultipart()
msg.attach(MIMEText(html_msg, 'html', 'utf-8'))
attach1=MIMEText(open('test.txt','rb').read(), 'plain', 'utf-8')
attach1.add_header('Content-Disposition', 'attachment', filename='test.txt')
msg.attach(attach1)

msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = Header('哈哈哈', 'utf-8')

try:
    smtpobj = smtplib.SMTP_SSL(smtp_server, 465)
    smtpobj.login(from_addr, password)
    # 发送邮件
    smtpobj.sendmail(from_addr, to_addr, msg.as_string())
    print("邮件发送成功")
    try:
        smtpobj.quit()
        print("连接正常关闭")
    except Exception as e:
        print("关闭连接时发生错误:", e)
except smtplib.SMTPException as e:
    print("SMTP错误:", e)
except Exception as e:
    print("发送邮件时发生错误:", e)